#!/usr/bin/perl

use warnings;
use strict;


use Date::ICal;
use Data::ICal;
use Data::ICal::Entry::Event;

use LWP::UserAgent;
use HTTP::Request;
use XML::Simple;
use Data::Dumper;
sub dumper { print Dumper(\@_) }

# the url of the xml file you want to access include the http://
my $feedurl = shift or die "Please give a RSS2 Feed as first Argument";

# set max number of seconds to access feed
my $timeout = 30;

my $xml = getFeed($feedurl);
my $xmlHash = XMLin($xml);
my $ical = makeIcal($xmlHash->{channel}->{item});

print $ical->as_string;

exit;

###################################################
# SUBS
###################################################
sub makeIcal {
  my $items = shift || die 'No Array';

  my $ical = Data::ICal->new(
      method => 'request',
  );

  foreach my $item (@$items){
   my $event = Data::ICal::Entry::Event->new();
   $item->{'dc:date'} =~ s/[\:\-]//sig;
   my $icalDate = Date::ICal->new( ical => $item->{'dc:date'} );
   $icalDate->add(duration => 'P0WT0H90M0S');
   
#   $item->{description} =~ s/\<.+?\>/\n/sig;

   $event->add_properties(
      summary        => $item->{title},
      description    => $item->{description}."\n",
      dtstart        => Date::ICal->new( ical => $item->{'dc:date'} )->ical,
      dtend          => $icalDate->ical,
      created        => Date::ICal->new( epoch => time )->ical,
      'last-modified'=> Date::ICal->new( epoch => time )->ical,
      class          => 'PUBLIC',
      priority       => 5,
      sequence       => 0,
      transp         => 'OPAQUE',
   );
   $ical->add_entry($event);
  }
  return $ical;
}


sub getFeed {
  my $feedurl = shift || die 'No Feedurl';
  
  my $ua = LWP::UserAgent->new();
  
  # set time out for accessing page
  $ua->timeout($timeout);
  
  # get page from actual website
  my $req = HTTP::Request->new(GET => $feedurl);
  my $res = $ua->request($req);
  
  	if ($res->is_success) {
  	 	return $res->content;
  	} else {
      die $res->error;
    }
}


